package com.yc.system.service.impl;

import com.yc.common.constant.Constant;
import com.yc.common.constant.RabbitMQConstant;
import com.yc.common.core.domain.model.Captcha;
import com.yc.common.core.redis.RedisCache;
import com.yc.common.utils.CaptchaGeneratorUtil;
import com.yc.system.service.IEmailCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("emailCodeConsumerService")
public class EmailCodeServiceImpl implements IEmailCodeService {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailCodeServiceImpl.class);
    
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean sendEmailCode(String email) {
        try {
            // 创建验证码对象
            Captcha captcha = new Captcha();
            captcha.setCaptcha(CaptchaGeneratorUtil.extracted().toString());
            System.out.println(captcha.getCaptcha());
            captcha.setCreateTime(System.currentTimeMillis());

            // 保存验证码到Redis的List
            String redisKey = Constant.Captcha.EMAIL_CODE_PREFIX + email;
            redisCache.appendToCacheList(redisKey, captcha, Constant.Captcha.CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);

            // 发送到消息队列
            Map<String, String> message = Map.of(
                    "email", email,
                    "code", captcha.getCaptcha()
            );
            rabbitTemplate.convertAndSend(
                    RabbitMQConstant.EMAIL.EMAIL_CODE_EXCHANGE,
                    RabbitMQConstant.EMAIL.EMAIL_CODE_ROUTING_KEY,
                    message
            );
            return true;
        } catch (Exception e) {
            logger.error("发送验证码失败: {}", e.getMessage(), e);
            return false;
        }
    }


    @Override
    public boolean verifyCode(String email, String code) {
        try {
            String redisKey = Constant.Captcha.EMAIL_CODE_PREFIX + email;
            List<Captcha> captchas = redisCache.getCacheList(redisKey);

            if (captchas == null || captchas.isEmpty()) {
                throw new RuntimeException("验证码已过期，请重新获取");
            }

            // 当前时间
            long currentTime = System.currentTimeMillis();

            // 遍历验证码列表
            Iterator<Captcha> iterator = captchas.iterator();
            while (iterator.hasNext()) {
                Captcha captcha = iterator.next();
                // 验证码匹配且未过期
                if (captcha.getCaptcha().equals(code) &&
                        currentTime - captcha.getCreateTime() <= Constant.Captcha.CODE_EXPIRE_MINUTES * 60 * 1000) {
                    // 验证成功
                    // 删除已验证的验证码
                    iterator.remove();
                    redisCache.setCacheList(redisKey, captchas);
                    return true;
                }
            }
            throw new RuntimeException("验证码不正确或已过期");
        } catch (Exception e) {
            logger.error("验证码验证失败: {}", e.getMessage(), e);
            return false;
        }
    }
} 